import { Component, useState, useEffect } from 'react';
import { View, Input } from '@tarojs/components'
import { toast, goBack, loginData } from '@/utils/utils';
import { fakeStudentWithWechat } from '@/server/login'
import { fetchWechatAuth, fakeSendSmsCode, } from "@/server/login";
import { wechatAuth } from "@/utils/utils";
import Taro, { useDidShow } from '@tarojs/taro'
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '@/reducers'
import './index.scss';
const login = (props) => {
  const [data, setData] = useState({
    mobile: '',
    smsCode: '',
  });
  useDidShow(() => {
    const data = Taro.getStorageSync("userInfo") || {};
    const { organizationId } = data;
    wechatAuth((e) => {
      fetchWechatAuth({ code: e, organizationId: organizationId }).then((val) => {
        const { userInfo = {} } = val
        const { unionId, openId, token } = userInfo
        if (token) {
          Taro.setStorageSync('userInfo', { ...loginData() || {}, ...userInfo });
          goBack()
          return
        }
        setData({
          ...data,
          unionId, openId
        })

      });
    });
  })
  const { mobile, smsCode } = data;
  const [rule, setRule] = useState('1');
  const [createTime, setCreateTime] = useState(60);
  const [visible, setVisble] = useState(true);
  const fetchCode = () => {
    if (!smsRule() && visible) {
      toast('请输入完整的手机号码 ');
    } else {
      if (!visible) {
        return;
      }
      fakeSendSmsCode({
        mobile: mobile,
        smsType: 'organizationAdminLogin'
      }).then(val => {
        let count = 0;
        setVisble(() => {
          let time = setInterval(() => {
            if (createTime <= 0 || count >= 60) {
              clearInterval(time);
              setVisble(() => {
                setCreateTime(60);
                return true;
              });
            } else {
              count += 1;
              setCreateTime(createTime - count);
            }
          }, 1000);
          return false;
        });
      })
    }
  };
  const smsRule = () => {
    if (mobile.length === 11) {
      return true;
    } else {
      return false;
    }
  };
  const fakeMobile = (e) => {
    const { mobile, smsCode, unionId, openId } = data;
    const useData = Taro.getStorageSync("userInfo") || {};
    const { organizationId } = useData;
    if (!mobile || !smsCode) {
      toast('请填写完整信息后注册');
    } else {
      const payload = {
        ...useData,
        ...data,
        mobile,
        smsCode,
        source: 'miniProgram',
        organizationId: Taro.getStorageSync("userInfo").organizationId || '1'

      }
      fakeStudentWithWechat(payload).then(e => {
        const { userInfo } = e;
        Taro.setStorageSync('userInfo', { ...loginData() || {}, unionId, openId, organizationId, ...userInfo });
        goBack()
      })
    }
  }
  return (
    <View className="register_login_box">
      <View className="register_login_logo"></View>
      <View className="register_login_users">
        <View className="register_input_info flex_mobile">
          <Input
            onInput={(e) => {
              console.log(e)
              setData({
                ...data,
                mobile: e.target.value,
              });
            }}
            value={mobile}
            placeholder="请输入手机号码"
          />
          <View
            className="register_getSms"
            onClick={() => {
              fetchCode();
            }}
          >
            {visible ? '获取验证码' : `重新获取（${createTime}）`}
          </View>
        </View>
        <Input
          className="register_input_info"
          onInput={(e) => {
            setData({
              ...data,
              smsCode: e.target.value,
            });
          }}
          placeholder="请输入手机验证码"
        />
      </View>
      <View className="register_login_btn" onClick={() => fakeMobile()}>
        登录
      </View>
    </View>
  );
};
export default login
